package com.jh.user.business.impl;

import cn.jh.common.exception.ServiceException;
import cn.jh.common.utils.BeanUtil;
import cn.jh.common.utils.CommonConstants;
import cn.jh.common.utils.DateUtil;
import cn.jh.common.utils.ObjToMap;
import com.jh.user.business.FastSilverPicPathBusiness;
import com.jh.user.business.ShopRegisterBussiness;
import com.jh.user.pojo.*;
import com.jh.user.pojo.enums.BaseEnums;
import com.jh.user.pojo.enums.ShopRegisterStatusEnums;
import com.jh.user.repository.*;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.sql.SQLException;
import java.util.*;

import static io.jsonwebtoken.lang.Strings.hasText;
import static org.apache.commons.lang3.StringUtils.isNotBlank;

@Service
public class ShopRegisterBussinessImpl implements ShopRegisterBussiness {

    private Logger LOG = LoggerFactory.getLogger(ShopRegisterBussinessImpl.class);

    private static final String errorInfo = "获取商户信息失败！";

    private final ShopRegisterRepository shopRegisterRepository;
    private final UserRepository userRepository;
    private final PlatformRepository platformRepository;
    private final JdbcTemplate jdbcTemplate;
    private final EntityManager entityManager;
    private final UserRoleRepository userRoleRepository;
    private final ProvinceRepository provinceRepository;
    private final CityRepository cityRepository;
    private final FastSilverPicPathRepository fastSilverPicPathRepository;
    private final FastSilverPicPathBusiness fastSilverPicPathBusiness;

    @Value("${shop.read_img_path}")
    private String readImgPath;
    @Value("${shop.register_pay_rate}")
    String registerPatRate;

    @Autowired
    public ShopRegisterBussinessImpl(ShopRegisterRepository shopRegisterRepository, UserRepository userRepository,
                                     PlatformRepository platformRepository, JdbcTemplate jdbcTemplate, EntityManager entityManager,
                                     UserRoleRepository userRoleRepository, ProvinceRepository provinceRepository, CityRepository cityRepository,
                                     FastSilverPicPathRepository fastSilverPicPathRepository, FastSilverPicPathBusiness fastSilverPicPathBusiness) {
        this.shopRegisterRepository = shopRegisterRepository;
        this.userRepository = userRepository;
        this.platformRepository = platformRepository;
        this.jdbcTemplate = jdbcTemplate;
        this.entityManager = entityManager;
        this.userRoleRepository = userRoleRepository;
        this.provinceRepository = provinceRepository;
        this.cityRepository = cityRepository;
        this.fastSilverPicPathRepository = fastSilverPicPathRepository;
        this.fastSilverPicPathBusiness = fastSilverPicPathBusiness;
    }

    private Specification<ShopRegister> where(final String shopId, final String legalName, final String startTime, final String endTime,final Integer status) {
        return (root, criteriaQuery, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<Predicate>();
            if (isNotBlank(shopId)) {
                predicates.add(criteriaBuilder.equal(root.<String>get("shopId"), shopId));
            }
            if (isNotBlank(legalName)) {
                predicates.add(criteriaBuilder.equal(root.<String>get("legalName"), legalName));
            }
            if (isNotBlank(startTime)) {
                String startTime_new = startTime+" 00:00:00";
                predicates.add(criteriaBuilder.greaterThan(root.<Date>get("createTime"), DateUtil.getYYMMHHMMSSDateFromStr(startTime_new)));
            }
            if (isNotBlank(endTime)) {
                String endTime_new = endTime+" 23:59:59";
                predicates.add(criteriaBuilder.lessThan(root.<Date>get("createTime"), DateUtil.getYYMMHHMMSSDateFromStr(endTime)));
            }
            if (status!=null) {
                predicates.add(criteriaBuilder.equal(root.<Integer>get("status"), status));
            }
            return criteriaQuery.where(predicates.toArray(new Predicate[predicates.size()])).getRestriction();
        };
    }

    @Override
    public Page<ShopRegister> findByShopIdAndLegalNameAndCreateTimeLessThanAndCreateTimeGreaterThan(String shopId, String legalName, String startTime, String endTime,Integer status, Pageable pageable) {
        return shopRegisterRepository.findAll(where(shopId, legalName, startTime, endTime,status), pageable);
    }
    @Override
    public Map<String, Object> findShopRegisterByWheres(String shopId,String shopName,String phone,Date startTime, long brandId,String preUserPhone,Pageable pageable) {
        Page<ShopRegister> shopRegisterPage = shopRegisterRepository.findAll(wheres(shopId, shopName, phone, startTime, brandId, preUserPhone), pageable);

        // 处理分页结果
        Map<String, Object> resMap = new HashMap<>();
        handleSHopRegisterPage(resMap, shopRegisterPage);
        return resMap;
    }

    /**
     * 处理分页结果
     * @param resMap
     * @param shopRegisterPage
     */
    private void handleSHopRegisterPage(Map<String, Object> resMap, Page<ShopRegister> shopRegisterPage) {
        long totalElements = shopRegisterPage.getTotalElements();
        boolean last = shopRegisterPage.isLast();
        int totalPages = shopRegisterPage.getTotalPages();
        int number = shopRegisterPage.getNumber();
        int size = shopRegisterPage.getSize();
        boolean first = shopRegisterPage.isFirst();
        Sort sort = shopRegisterPage.getSort();
        int numberOfElements = shopRegisterPage.getNumberOfElements();

        resMap.put("totalElements", totalElements);
        resMap.put("last", last);
        resMap.put("totalPages", totalPages);
        resMap.put("number", number);
        resMap.put("size", size);
        resMap.put("first", first);
        resMap.put("sort", sort);
        resMap.put("numberOfElements", numberOfElements);

        List<ShopRegister> content = shopRegisterPage.getContent();
        if (content.size() == 0) {
            resMap.put("content", new ArrayList<ShopRegister>());
        } else {
            List<Map<String, Object>> list = new ArrayList<>();
            // 获取快银上传图片信息
            List<FastSilverPicPath> fastSilverPicPathList = fastSilverPicPathRepository.findAll();

            for (ShopRegister shopRegister : content) {
                Long userId = shopRegister.getUserId();
                // 此map必须放置外层for循环
                Map<String, Object> map = new HashMap<>();
                shopRegisterToMap(map, shopRegister);
                if (fastSilverPicPathList.size() > 0) {
                    for (FastSilverPicPath fastSilverPicPath : fastSilverPicPathList) {
                        long fastUserId = fastSilverPicPath.getUserId();
                        if (userId != fastUserId) {
                            continue;
                        }
                        fastSilverPicPathToMap(map, fastSilverPicPath);
                    }
                }
                list.add(map);
            }
            resMap.put("content", list);
        }
    }

    /**
     * 封装商户进件map
     * @param map
     * @param shopRegister
     */
    private void shopRegisterToMap(Map<String, Object> map, ShopRegister shopRegister) {
        Map<String, Object> shopRegisterToMap = ObjToMap.ConvertObjToMap(shopRegister);

        assert shopRegisterToMap != null;
        shopRegisterToMap.remove("businessPic");
        shopRegisterToMap.remove("legalIdPic");
        shopRegisterToMap.remove("legalIdBackPic");
        shopRegisterToMap.remove("shopHeadPic");
        shopRegisterToMap.remove("firstPic");
        shopRegisterToMap.remove("accountPic");
        shopRegisterToMap.remove("bankFrontPic");
        shopRegisterToMap.remove("bankReversePic");
        shopRegisterToMap.remove("mchScenePic");
        shopRegisterToMap.remove("relationshipPic");
        shopRegisterToMap.remove("merchantPic");
        shopRegisterToMap.remove("shopIdNumExTimeStr");
        shopRegisterToMap.remove("legalExTimeStr");
        shopRegisterToMap.remove("provinceId");
        shopRegisterToMap.remove("cityId");

        map.putAll(shopRegisterToMap);
    }

    /**
     * 封装快银上传图片map
     * @param map
     * @param fastSilverPicPath
     */
    private void fastSilverPicPathToMap(Map<String, Object> map, FastSilverPicPath fastSilverPicPath) {
        FastSilverPicPathResponse fsppResponse = new FastSilverPicPathResponse();
        fsppResponse.addFastSilverPicPathResponse(fastSilverPicPath);

        Map<String, Object> fastSilverPicPathToMap = ObjToMap.ConvertObjToMap(fsppResponse);

        assert fastSilverPicPathToMap != null;
        fastSilverPicPathToMap.remove("id");
        fastSilverPicPathToMap.remove("userId");
        fastSilverPicPathToMap.remove("updateTime");
        fastSilverPicPathToMap.remove("createTime");

        map.putAll(fastSilverPicPathToMap);
    }

    private Specification<ShopRegister> wheres(final String shopId,final String shopName,final String phone,final Date startTime,final long brandId,final String preUserPhone) {
        return new Specification<ShopRegister>() {
            public Predicate toPredicate(Root<ShopRegister> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder cb) {
                List<Predicate> predicates = new ArrayList<Predicate>();
                if (isNotBlank(shopId)) {
                    predicates.add(cb.equal(root.<String>get("shopId"), shopId));
                }
                if (isNotBlank(shopName)) {
                    predicates.add(cb.like(root.<String>get("shopName"),"%" + shopName + "%"));
                }
                if (isNotBlank(phone)) {
                    predicates.add(cb.like(root.<String>get("mobilePhone"),"%" + phone + "%"));
                }
                if (startTime != null) {
                    predicates.add(cb.greaterThan(root.<Date>get("createTime"), startTime));
                }
                if (brandId != -1) {
                    predicates.add(cb.equal(root.<String>get("brandId"), brandId));
                }
                if (isNotBlank(preUserPhone)) {
                    predicates.add(cb.equal(root.<String>get("agentPhone"),preUserPhone));
                }
                return criteriaQuery.where(predicates.toArray(new Predicate[predicates.size()])).getRestriction();
            }
        };
    }

    @Transactional
    @Override
    public ShopRegister mergeShopRegister(ShopRegister shopRegister) throws ServiceException {
        ShopRegister register = shopRegisterRepository.findByMobilePhone(shopRegister.getMobilePhone());
        if (register != null) {
            throw new ServiceException("商户进件手机号码重复");
        }
        shopRegister.setUpdateTime(new Date());
        shopRegister.setCreateTime(new Date());
        shopRegister.setShopId(System.currentTimeMillis() + "" + new Random().nextInt(5));
        shopRegister.setStatus(ShopRegisterStatusEnums.VERIFY.getValue());

        return shopRegisterRepository.saveAndFlush(shopRegister);
    }

    @Override
    public ShopRegister findById(Long id) {
        return shopRegisterRepository.findById(id);
    }


    @Override
    @Transactional
    public ShopRegister update(ShopRegister shopRegister) throws ServiceException { //商铺信息修改
        // 一些属性不予修改
        shopRegister.notUpdateProps();

        ShopRegister existsRegister = shopRegisterRepository.findById(shopRegister.getId());
        if (existsRegister == null) {
            throw new ServiceException("商户进件信息不存在");
        }
        // 如果没有传图片则替换成已保存在数据表中的图片信息
        shopRegister = shopRegister.storeExistsPic(shopRegister, existsRegister);

        shopRegister.setBrandId(existsRegister.getBrandId());
        BeanUtil.copyPropertiesIgnoreNull(shopRegister, existsRegister);
        entityManager.merge(existsRegister);
        entityManager.flush();
        return existsRegister;
    }

    @Transactional
    public void updateShopRegister(ShopRegister shopRegister)throws SQLException{
        String sql = "update t_shop_register set agent_phone = " + shopRegister.getAgentPhone();
        if(isNotBlank(shopRegister.getWechatAppId())){
            sql += " ,wechat_app_id = " + shopRegister.getWechatAppId();
        }

        if(isNotBlank(shopRegister.getAlipayAppId())){
            sql += " ,alipay_app_id = " + shopRegister.getAlipayAppId();
        }
        sql += " where mobile_phone = " + shopRegister.getMobilePhone();
        jdbcTemplate.update(sql);
    }

    @Transactional
    @Override
    public ShopRegister updateShopPayConfigure(@NotNull String shopId, String alipayAppId, String wechatAppId) throws ServiceException {
        ShopRegister register = shopRegisterRepository.findByShopId(shopId);
        if(register == null){
            throw new ServiceException("商户不存在，请确认！");
        }
        if(register.getStatus() != 5){
            throw new ServiceException("商户未激活，请确认！");
        }
        if (hasText(alipayAppId) || hasText(wechatAppId)) {
            if (hasText(alipayAppId)) {
                register.setAlipayAppId(alipayAppId);
                register.setAlipaySwitch("1");
            }
            if (hasText(wechatAppId)) {
                register.setWechatAppId(wechatAppId);
                register.setWechatSwitch("1");
            }
            shopRegisterRepository.saveAndFlush(register);
        }
        return register;
    }

    @Transactional
    @Override
    public ShopRegister supplyShopPayConfigure(@NotNull String shopId, String alipayAppId, String wechatAppId) throws ServiceException {
        ShopRegister register = shopRegisterRepository.findByShopId(shopId);
        if(register == null){
            throw new ServiceException("商户不存在，请确认！");
        }
        if(register.getStatus() != 5){
            throw new ServiceException("商户未激活，请确认！");
        }
        if (hasText(alipayAppId) || hasText(wechatAppId)) {
            if (hasText(alipayAppId) && !Objects.equals(register.getAlipayAppId(), alipayAppId)) {
                register.setAlipayAppId(alipayAppId);
                register.setAlipaySwitch("1");
                shopRegisterRepository.saveAndFlush(register);
            }
            if (hasText(wechatAppId) && !Objects.equals(register.getWechatAppId(), wechatAppId)) {
                register.setWechatAppId(wechatAppId);
                register.setWechatSwitch("1");
                shopRegisterRepository.saveAndFlush(register);
            }
        }
        return register;
    }

    @Override
    public void verify(Long id, Integer status) {
        ShopRegister register = shopRegisterRepository.findById(id);
        if (BaseEnums.FALSE.getValue() == status){
            register.setStatus(ShopRegisterStatusEnums.FRIST_ERROR.getValue());
            entityManager.merge(register);
            entityManager.flush();
        }else {
            register.setStatus(ShopRegisterStatusEnums.SUCCESS.getValue());
            entityManager.merge(register);
            entityManager.flush();
        }
    }

    @Override
    public ShopRegister findByUserId(Long userId) {
        return shopRegisterRepository.findByUserId(userId);
    }

    private void imgUpdate(ShopRegister shopRegister){
     /*   shopRegister.setLegalIdBackPic(shopRegister.getLegalIdBackPic().replaceAll(readImgPath,""));
        shopRegister.setShopHeadPic(shopRegister.getShopHeadPic().replaceAll(readImgPath,""));
        shopRegister.setLegalIdPic(shopRegister.getLegalIdPic().replace(readImgPath,""));
        shopRegister.setRelationshipPic(shopRegister.getRelationshipPic().replace(readImgPath,""));
        shopRegister.setMerchantPic(shopRegister.getMerchantPic().replace(readImgPath,""));
        shopRegister.setRelationshipPic(shopRegister.getRelationshipPic().replace(readImgPath,""));
        shopRegister.setFirstPic(shopRegister.getFirstPic().replace(readImgPath,""));
        shopRegister.setBusinessPic(shopRegister.getBusinessPic().replace(readImgPath,""));*/
    }

    @Override
    public ShopRegister findShopRegister(String platformCode) {

        if (!hasText(platformCode)) {
            return null;
        }
        Platform platform = platformRepository.findByPlatformCodeAndState(platformCode, "2");
        System.out.println("44444====>platform"+platform);
        if (platform == null) {
            return null;
        }
        return queryShopRegister(platform);
    }

    @Override
    public ShopRegister findShopRegister(String platformCode, String channel) throws ServiceException {
        if (!hasText(platformCode) || !hasText(channel)) {
            throw new ServiceException("缺少必要参数");
        }
        Platform platform = platformRepository.findByPlatformCode(platformCode);
        if (platform == null) {
            throw new ServiceException("台码信息不存在");
        }
        platform.activeValidation();

        ShopRegister shopRegister = queryShopRegister(platform);
        if (shopRegister == null) {
            return null;
        }

        // 查询商户渠道是否开通
//        URI uri = util.getServiceUrl("paymentchannel", "error url request!");
//        String url = uri.toString() + "/v1.0/paymentchannel/query/channel?shopId=" + shopRegister.getShopId() + "&channel=" + channel;
//        RestTemplate restTemplate = new RestTemplate();
//        String result = restTemplate.getForObject(url, String.class);
//        JSONObject jsonObject = JSONObject.fromObject(result);
//        if (!Objects.equals(jsonObject.getString(CommonConstants.RESP_CODE), CommonConstants.SUCCESS)) {
//            throw new ServiceException(jsonObject.getString(CommonConstants.RESP_MESSAGE));
//        }
        return shopRegister;
    }

    @Override
    public ShopRegister findShopRegisterByShopId(String shopId) {

        if (!hasText(shopId)) {
            return null;
        }
        Platform platform = platformRepository.findByShopIdAndState(shopId, "2");

        if (platform == null) {
            return null;
        }
        return queryShopRegister(platform);
    }
    @Override
    public ShopRegister queryShopRegister(Platform platform){
        String sql = "select s.* from t_user t, t_shop_register s, t_platform p where s.user_id = t.id and p.shop_id = t.phone and t.phone = '" + platform.getShopId()+"'";
        List<ShopRegister> list = jdbcTemplate.query(sql,new BeanPropertyRowMapper<>(ShopRegister.class));
        ShopRegister shopRegister = new ShopRegister();
        if (!list.isEmpty()){
            shopRegister = list.get(0);
        }
        return shopRegister;
    }
    /**根据代理商手机号agentPhone查询商户*/
    public List<ShopRegister> findShopRegistersByAgentPhone(String agentPhone){
        return shopRegisterRepository.findShopRegistersByAgentPhone(agentPhone);
    }

    @Override
    public ShopRegister findByMobilePhone(String mobilePhone) throws ServiceException{
        ShopRegister shopRegister = shopRegisterRepository.findByMobile(mobilePhone);
//        if (null == shopRegister) {
//            throw new ServiceException("无商户进件信息！");
//        }
        setProvinceAndCity(shopRegister);
        return shopRegister;
    }

    @Override
    public ShopRegister findByShopId(String id) {
        return shopRegisterRepository.findByShopId(id);
    }

    @Override
    public ShopRegister saveShopRegister(ShopRegister shopRegister) {
        ShopRegister result = shopRegisterRepository.save(shopRegister);
        return result;
    }

    @Override
    public String getUsernInfoByShopRegister(long userId, String shopName, String shopPhone) throws ServiceException {
        StringBuffer sb = new StringBuffer();
        UserRole userRole = userRoleRepository.queryUserRole(userId);
        if (null == userRole) {
            throw new ServiceException("获取用户角色信息失败！");
        }
        long roleId = userRole.getRoleId();
        if (!CommonConstants.ROLE_ID_06.equals(roleId)) {
            throw new ServiceException("非台卡代理无法查看商铺交易信息！");
        }

        // 获取带卡代理的用户信息
        User user = userRepository.findUserById(userId);
        String phone = user.getPhone();
        if (StringUtils.isNotEmpty(shopName)) {

            // 获取台卡代理信息
            List<Platform> platformList = platformRepository.findByAgent(phone);
            if (null == platformList || platformList.size() == 0) {
                throw new ServiceException("获取台卡代理信息失败！");
            }

            List<ShopRegister> shopRegisterList = shopRegisterRepository.findByShopName(shopName);
            if (null == shopRegisterList) {
                throw new ServiceException(errorInfo);
            }

            List<ShopRegister> shopRegisterList1 = new ArrayList<>();

            // 校验商户信息是否属于该台卡代理
            for (ShopRegister shopRegister : shopRegisterList) {
                String mobilePhone = shopRegister.getMobilePhone();
                for (Platform platform : platformList) {
                    String shopId = platform.getShopId();
                    if (StringUtils.isNotEmpty(shopId) && mobilePhone.equals(shopId)) {
                        // 有相等的手机号
                        shopRegisterList1.add(shopRegister);
                    }
                }
            }

            if (null != shopRegisterList1 && shopRegisterList1.size() > 0) {
                for (ShopRegister shopRegister : shopRegisterList1) {
                    sb.append(shopRegister.getUserId() + ",");
                }
            }
            if (sb.length() > 1) {
                return sb.substring(0, sb.length() - 1);
            } else {
                throw new ServiceException(errorInfo);
            }
        }

        if (StringUtils.isNotEmpty(shopPhone)) {// 获取台卡代理信息
            List<Platform> platformList = platformRepository.findByAgent(phone);
            if (null == platformList || platformList.size() == 0) {
                throw new ServiceException("获取台卡代理信息失败！");
            }
            Boolean flag = true;
            for (Platform platform : platformList) {
                String shopId = platform.getShopId();
                if (shopId.equals(shopPhone)) {
                    flag = false;
                    break;
                }
            }
            if (flag) {
                throw new ServiceException("您未代理该商户！");
            }

            ShopRegister shopRegister = shopRegisterRepository.findByMobilePhone(shopPhone);
            if (null == shopRegister) {
                throw new ServiceException(errorInfo);
            }
            sb.append(shopRegister.getUserId());
            if (sb.length() > 1) {
                return sb.toString();
            } else {
                throw new ServiceException(errorInfo);
            }
        }
        throw new ServiceException(errorInfo);
    }

    @Override
    public ShopRegister getByShopId(long userId, String merchantNo) {
        return shopRegisterRepository.getByUserIdAndShopId(userId, merchantNo);
    }

    @Override
    public Map<String, String> getShopRegisterByShopId(String shopId) throws ServiceException {
        ShopRegister shopRegister = shopRegisterRepository.getShopRegisterByShopId(shopId, 407, 5);
        if (null == shopRegister) {
            throw new ServiceException("未查询到商户信息！");
        }
        String shopName = shopRegister.getShopName();
        Long userId = shopRegister.getUserId();

        Map<String, String> map = new HashMap<>();
        map.put("shopName", shopName);
        map.put("userId", userId + "");
        return map;
    }

    @Override
    public Map<String, Object> getShopRegisterByUserId(long userId) throws ServiceException {
        ShopRegister byUserId = shopRegisterRepository.findShopRegister(userId, 407, 5);
        if (null == byUserId) {
            throw new ServiceException("未查询到商户信息！");
        }
        String shopName = byUserId.getShopName();
        String shopId = byUserId.getShopId();
        String shopProvinces = byUserId.getShopProvinces();
        String shopCity = byUserId.getShopCity();
        String shopAddress = byUserId.getShopAddress();
        String shopShortName = byUserId.getShopShortName();

        Map<String, Object> map = new HashMap<>();
        map.put("shopName", shopName);
        map.put("shopId", shopId);
        map.put("shopProvinces", shopProvinces);
        map.put("shopCity", shopCity);
        map.put("shopAddress", shopAddress);
        map.put("shopShortName", shopShortName);
        return map;
    }

    @Override
    public Map<String, Object> queryByMobilePhone(String mobilePhone) throws ServiceException {
        ShopRegister shopRegister = shopRegisterRepository.findByMobile(mobilePhone);
        if (null == shopRegister) {
            ShopRegister register = new ShopRegister();
            return setShopRegisterMap(register);
        }
        setProvinceAndCity(shopRegister);

        return setShopRegisterMap(shopRegister);
    }

    @Override
    @Transactional
    public Map<String, Object> manageBankgroundPurchase(ShopRegister shopRegister, FastSilverPicPathRequest sfppRequest) throws ServiceException {
        setProvinceAndCity(shopRegister);

        String mobilePhone = shopRegister.getMobilePhone();
        ShopRegister exist = shopRegisterRepository.findByMobile(mobilePhone);
        User user = userRepository.findUserByPhone(mobilePhone);
        sfppRequest.setUserId(user.getId());
        if (null == exist) {
            // 商户进件
            shopRegister.setBrandId(user.getBrandId());
            shopRegister.setPayRate(new BigDecimal(registerPatRate));
            shopRegister.setUserId(user.getId());
            shopRegister.setStatus(ShopRegisterStatusEnums.VERIFY.getValue());
            shopRegister.setShopId(System.currentTimeMillis() + "" + new Random().nextInt(5));

            ShopRegister register = shopRegisterRepository.save(shopRegister);
            Integer status = register.getStatus();

            fastSilverPicPathBusiness.uploadPics(sfppRequest);

            if (status == 1 || status == 2 || status == 5) {
                user.setShopsStatus(status == 1 ? "0" : (status == 2 ? "2" : "1"));
                userRepository.updateShopStatus(user.getShopsStatus(), user.getId());
            }
            return setShopRegisterMap(register);
        } else {
            // 商户修改
            exist.setStatus(ShopRegisterStatusEnums.VERIFY.getValue());
            BeanUtil.copyPropertiesIgnoreNull(shopRegister, exist);
            entityManager.merge(exist);
//            exist.modifyShopRegister(shopRegister);
            shopRegisterRepository.save(exist);
            fastSilverPicPathBusiness.uploadPics(sfppRequest);

            Integer status = exist.getStatus();
            if (status == 1 || status == 2 || status == 5) {
                user.setShopsStatus(status == 1 ? "0" : (status == 2 ? "2" : "1"));
                userRepository.updateShopStatus(user.getShopsStatus(), user.getId());
            }
            return setShopRegisterMap(exist);
        }
    }

    private Map<String, Object> setShopRegisterMap(ShopRegister shopRegister) {
        Map<String, Object> shopRegisterMap = ObjToMap.ConvertObjToMap(shopRegister);
        assert shopRegisterMap != null;
        shopRegisterMap.remove("businessPic");
        shopRegisterMap.remove("legalIdPic");
        shopRegisterMap.remove("legalIdBackPic");
        shopRegisterMap.remove("shopHeadPic");
        shopRegisterMap.remove("firstPic");
        shopRegisterMap.remove("accountPic");
        shopRegisterMap.remove("bankFrontPic");
        shopRegisterMap.remove("bankReversePic");
        shopRegisterMap.remove("mchScenePic");
        shopRegisterMap.remove("relationshipPic");
        shopRegisterMap.remove("merchantPic");

        Long userId = shopRegister.getUserId();
        FastSilverPicPathResponse fsppResponse = new FastSilverPicPathResponse();
        if (null != userId) {
            FastSilverPicPath fastSilverPicPath = fastSilverPicPathRepository.queryByUserId(userId);
            fsppResponse.addFastSilverPicPathResponse(fastSilverPicPath);
        }

        Map<String, Object> fsPicPathMap = ObjToMap.ConvertObjToMap(fsppResponse);
        assert fsPicPathMap != null;
        fsPicPathMap.remove("id");
        fsPicPathMap.remove("userId");

        shopRegisterMap.putAll(fsPicPathMap);
        return shopRegisterMap;
    }

    private void setProvinceAndCity(ShopRegister shopRegister) {
        if (null != shopRegister) {
            String shopProvinces = shopRegister.getShopProvinces();
            String shopCity = shopRegister.getShopCity();

            if (StringUtils.isNotEmpty(shopProvinces)) {
                Province province = provinceRepository.queryByProvince(shopProvinces);
                if (null != province) {
                    shopRegister.setProvinceId(province.getProvinceid());
                }
            }
            if (StringUtils.isNotEmpty(shopCity)) {
                City city = cityRepository.queryByCity(shopCity);
                if (null != city) {
                    shopRegister.setCityId(city.getCityid());
                }
            }
        }
    }

    @Override
    public Page<ShopRegister> findByWhere(String shopid, String shopname, String phone, Integer status,Pageable pageable) {
        return shopRegisterRepository.findAll(where_2(shopid, shopname, phone,status), pageable);
    }

    private Specification<ShopRegister> where_2(final String shopid, final String shopname, final String phone, final Integer status) {
        return (root, criteriaQuery, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<Predicate>();
            if (isNotBlank(shopid)) {
                predicates.add(criteriaBuilder.equal(root.<String>get("shopId"), shopid));
            }
            if (isNotBlank(phone)) {
                predicates.add(criteriaBuilder.equal(root.<String>get("mobilePhone"), phone));
            }
            if (isNotBlank(shopname)) {
                try{
                    String shopName = URLDecoder.decode(shopname,"UTF-8");
                    predicates.add(criteriaBuilder.equal(root.<String>get("shopName"), shopName));
                }catch (Exception e){

                }
            }

            if (status!=null) {
                predicates.add(criteriaBuilder.equal(root.<Integer>get("status"), status));
            }
            return criteriaQuery.where(predicates.toArray(new Predicate[predicates.size()])).getRestriction();
        };
    }
}
